<?php

namespace App\Admin\Controllers;
use Illuminate\Http\Request;
use App\Admin\Extensions\Tools\ReleasePost;
use Illuminate\Support\MessageBag;
use Validator;
use App\crm_customer;
use App\Admin_users;
use App\crm_route;
use App\crm_order;
use App\crm_biaoqian;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use App\Admin\Extensions\Tools\XinzengGender;
class Crm_kehuController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    // 客户添加
    public function store(Request $request)
    {
        //前端验证不得为空
        $list=$request->except("_token");
        $rule=[
            'customer_name'=>'required',
            'customer_phone'=>'required|size:11',
            'customer_sfz'=>'required|size:18',
            'customer_danwei'=>'required',
        ];
        $mess=[
            'customer_name.required'=>'客户姓名必须输入',
            'customer_phone.required'=>'客户电话必须输入',
            'customer_phone.size'=>'客户电话必须输入11位手机号码',
            'customer_sfz.required'=>'客户身份证必须输入',
            'customer_sfz.size'=>'客户身份证必须输入18位',
            'customer_danwei.required'=>'单位名称必须输入',
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行添加
            $list['customer_weihu']=Admin::user()->id;
            $list['customer_shengri']=substr($list['customer_sfz'],-8,4);
            $res=\DB::table('crm_customer')->insertGetid($list);
            if($res){
                $success = new MessageBag([
                    'title'   => '添加成功',
                ]);
                return redirect(admin_url('crm_kehu/info2/'.$res))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '添加失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }   
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    // 客户录入
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('客户录入');
            $content->description('录入');
            $form = new Form();
            $form->action(admin_url('crm_kehu'));
            $form->select('customer_laiyuan','客户来源')->options(['1'=>'网站','2'=>'转介绍','3'=>'上门','4'=>'电话销售','5'=>'老客户','6'=>'其他']);
            $form->text('customer_name', '客户姓名')->rules('required');
            $form->number('customer_age', '客户年龄')->rules('required');
            $form->select('customer_sex', '性别')->options(['1'=>'男','2'=>'女']);
            $form->text('customer_phone', '客户电话');
            $form->text('customer_weixin', '微信');
            $form->text('customer_qq', 'QQ');
            $form->email('customer_email','邮箱Email');
            $form->text('customer_sfz','身份证号码')->rules('required');
            $form->select('customer_type','客户类别')->options(['单位'=>'单位','个人'=>'个人']);
            $form->text('customer_danwei', '单位名称')->rules('required');
            $form->textarea('customer_beizhu','备注')->rows(5);
            $directors=Admin_users::find(Admin::user()->id)->pluck("username","username");
            $form->select('customer_weihu', '维护人')->options($directors)->attribute(['disabled' => true]);
            $form->hidden('customer_kfdate','开发时间')->default(date("y-m-d h:i:s"));
            $form->hidden('customer_kaifa','开发人')->default(Admin::user()->id);
            $content->body($form);
        });
    }
    //客户搜索
    public function info(Request $request)
    {
        $list=$request->except("_token");
        return Admin::content(function (Content $content) use ($list) {
            $content->header('客户搜索');
            // $content->description('description');
            $content->body($this->grid($list));
        });
    }
    // 单个搜索
    public function info2($id)
    {

        return Admin::content(function (Content $content) use ($id) {
            $content->header('客户搜索');
            // $content->description('description');
            $content->body($this->grid2($id));
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    //客户搜索
    protected function grid($list)
    {
        return Admin::grid(crm_customer::class, function (Grid $grid) use ($list) {
            if($list['customer_name'] && $list['customer_phone'] && $list['customer_sfz']){
                $grid->model()->where('customer_name', $list['customer_name'])->where('customer_phone', $list['customer_phone'])->where('customer_sfz', $list['customer_sfz']);
            }elseif($list['customer_name'] && $list['customer_sfz']){
                $grid->model()->where('customer_name', $list['customer_name'])->where('customer_sfz', $list['customer_sfz']);
            }elseif($list['customer_name'] && $list['customer_phone']){
                $grid->model()->where('customer_name', $list['customer_name'])->where('customer_phone', $list['customer_phone']);
            }elseif($list['customer_name']){
                $grid->model()->where('customer_name', $list['customer_name']);
            }elseif($list['customer_phone'] && $list['customer_sfz']){
                $grid->model()->where('customer_phone', $list['customer_phone'])->where('customer_sfz', $list['customer_sfz']);
            }elseif($list['customer_phone']){
                $grid->model()->where('customer_phone', $list['customer_phone']);
            }elseif($list['customer_sfz']){
                $grid->model()->where('customer_sfz', $list['customer_sfz']);
            }else{
                if(Admin::user()->isAdministrator()){
                
                }else{
                    $grid->model()->where('customer_weihu',Admin::user()->id);
                }
            }
            $grid->id('序号');
            $grid->customer_name('客户姓名');
            $grid->customer_phone('客户电话');
            $grid->customer_danwei('单位');
            $list=['1'=>'网站','2'=>'转介绍','3'=>'上门','4'=>'电话销售','5'=>'老客户','6'=>'其他'];
            $grid->column('customer_laiyuan','客户来源')->display(function ($customer_laiyuan) use ($list) {
                return $list[$customer_laiyuan];
            });
            $grid->column('admin_users.username','维护人');
            $grid->customer_kfdate('录入时间');
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // $batch->add('发布文章', new ReleasePost(1));
                    $batch->disableDelete();
                    $batch->add('下单', new ReleasePost());
                });
                $tools->append(new XinzengGender());
            });
            $grid->disableExport();//禁用导出数据
            $grid->disableFilter();//禁用查询过滤器
            $grid->disableCreation();//禁用创建按钮
            $grid->disableActions();
        });
    }
    // 单个搜索
    protected function grid2($id)
    {
        return Admin::grid(crm_customer::class, function (Grid $grid) use ($id) {
            $grid->model()->where('id', $id);
            $grid->id('序号');
            $grid->customer_name('客户姓名');
            $grid->customer_phone('客户电话');
            $grid->customer_danwei('单位');
            $list=['1'=>'网站','2'=>'转介绍','3'=>'上门','4'=>'电话销售','5'=>'老客户','6'=>'其他'];
            $grid->column('customer_laiyuan','客户来源')->display(function ($customer_laiyuan) use ($list) {
                return $list[$customer_laiyuan];
            });
            $grid->column('admin_users.username','维护人');
            $grid->customer_kfdate('录入时间');
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // $batch->add('发布文章', new ReleasePost(1));
                    $batch->disableDelete();
                    $batch->add('下单', new ReleasePost());
                });
                $tools->append(new XinzengGender());
            });
            $grid->disableExport();//禁用导出数据
            $grid->disableFilter();//禁用查询过滤器
            $grid->disableCreation();//禁用创建按钮
            $grid->disableActions();
        });
    }
    // 工单录入
    public function xiadan($id)
    {
        if(strpos($id,',')){
            $error = new MessageBag([
                    'title'   => '禁止批量下单',
                ]);
            return redirect(admin_url('crm_order'))->with(compact('error'));
        }
        return Admin::content(function (Content $content) use ($id) {
            $content->header('工单录入');
            $content->description('录入');
            $form = new Form();
            $form->action(admin_url('crm_kehu/tianjia'));
            $res=crm_route::where("parent_id",0)->get()->pluck("title","id");
            $form->select('order_didian','旅游类型')->options($res);
            $didian2=crm_route::where("parent_id",crm_route::where("parent_id",0)->first()->id)->pluck("title","id");
            $form->select('order_didian2', '旅游地点')->options($didian2);
            $form->text('order_xianlu','旅游线路');
            $biaoqian=crm_biaoqian::all()->pluck("name","id");
            $form->select('order_lvyouleibie','标签')->options($biaoqian);
            $form->date('order_lvyoudate', '出发时间');
            // $form->select('order_caozuoleibie','操作类别')->options(['自己' => '自己', '供应商' => '供应商']);
            // $form->text('order_statue','工单状态');
            $form->textarea('order_beizhu','工单备注')->rows(5);
            $form->hidden('order_customerid','客户ID')->default($id);
            $form->hidden('staff_id','员工ID')->default(Admin::user()->id);
            $form->hidden('order_orderdate','工单录入时间')->default(date("y-m-d h:i:s"));
            $script_addones=<<<EOT
                
                $(".order_didian").change(function(){
                    var id=$(".order_didian option:selected").val();
                    $.ajax({
                        url: "/admin/gdindex/ajax5",
                        type: "get",
                        dataType: "json",
                        data: {'v': id},
                        success:function(data){
                            var hh="<option value=\"请-选-择\">请-选-择<\/option>";
                            for(var i=0;i<data.length;i++){
                                hh +="<option value="
                                hh +=data[i].id
                                hh +=" >"
                                hh +=data[i].title
                                hh +="<\/option>";
                                // document.getElementsByClassName('order_didian2').options[i] = new Option(data[i].title,data[i].id);
                            }
                            $(".order_didian2").html(hh).parent().parent().css("display","block");;
                        }
                    }); 
                })

EOT;
            Admin::script($script_addones);
            $content->body($form);
        });
    }
    // 工单添加
    public function tianjia(Request $request)
    {
        //前端验证不得为空
        $list=$request->except("_token");
        $rule=[
            'order_didian'=>'required',
            'order_didian2'=>'required',
            'order_xianlu'=>'required',
            'order_lvyouleibie'=>'required',
            'order_lvyoudate'=>'required',
            'order_beizhu'=>'required',
        ];
        $mess=[
            'order_didian.required'=>'旅游类型必须输入',
            'order_didian2.required'=>'旅游地点必须输入',
            'order_xianlu.required'=>'旅游线路必须输入',
            'order_lvyouleibie.required'=>'标签必须输入',
            'order_lvyoudate.required'=>'旅游时间必须输入',
            'order_beizhu.required'=>'工单备注必须输入',
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行添加
            $res=\DB::table('crm_order')->insertGetid($list);
            if($res){
                $success = new MessageBag([
                    'title'   => '下单成功',
                ]);
                return redirect(admin_url('crm_order/'.$res.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '下单失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }
    }
    public function ajax5()
    {
        $id = $_GET['v'];
        $list = \DB::table('crm_route')->where('parent_id','=',$id)->get();
        echo json_encode($list);
    }
    public function ajax6()
    {
        $id = $_GET['v'];
        $list = \DB::table('supplier_type')->where('supplier_id',$id)->get();
        echo json_encode($list);
    }
    public function ajax7()
    {
        $id = $_GET['v'];
        $list = \DB::table('supplier_type')->where('id',$id)->first()->zhanghao;
        echo json_encode($list);
    }
}
